package tv.youxing.android.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.kaopiz.kprogresshud.KProgressHUD;
import com.kymjs.rxvolley.RxVolley;
import com.kymjs.rxvolley.client.HttpCallback;
import com.kymjs.rxvolley.client.HttpParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.hdodenhof.circleimageview.CircleImageView;
import tv.youxing.android.Interface.UpRefUpdateListener;
import tv.youxing.android.R;
import tv.youxing.android.adapter.AbsRecyclerAdater;
import tv.youxing.android.adapter.DynamicAdapter;
import tv.youxing.android.adapter.ImageAdapter;
import tv.youxing.android.custom.CustomToast;
import tv.youxing.android.custom.GridViewForScrollView;
import tv.youxing.android.entity.DianZhanModel;
import tv.youxing.android.entity.DynamicDetailsPingLunModel;
import tv.youxing.android.entity.FriendModel;
import tv.youxing.android.entity.ImageArrayModel;
import tv.youxing.android.ui.AddDynamicActivity;
import tv.youxing.android.ui.DynamicDetailsActivity;
import tv.youxing.android.ui.DynamicDetailsActivity_new;
import tv.youxing.android.ui.LoginActivity;
import tv.youxing.android.ui.test.XListView;
import tv.youxing.android.utils.AppConst;
import tv.youxing.android.utils.GsonUtils;
import tv.youxing.android.utils.PicassoUtils;
import tv.youxing.android.utils.ShareUtils;
import tv.youxing.android.utils.StaticClass;
import tv.youxing.android.utils.UtilTools;

/**
 * Created by apple on 2017/4/17.
 */

/**
 * 项目名：   youxing
 * 包名：     tv.youxing.android .fragment
 * 文件名：   FriendFragment
 * 创建者：   叶克武
 * 创建时间： 2017/4/17 下午2:49
 * 描述：    TODO
 */
public class FriendFragment extends Fragment implements XListView.IXListViewListener {


    FriendModel allData;


    @BindView(R.id.ll_login)
    LinearLayout ll_loign;
    @BindView(R.id.ll_not)
    LinearLayout ll_not;
    @BindView(R.id.login)
    TextView tvLogin;

    //发布说说
    @BindView(R.id.ivAddDynamic)
    ImageView ivAddDynamic;

    //广告列表
    AbsRecyclerAdater absAdapter;
    List<FriendModel.ResultBean.AdsBean> absLists = new ArrayList<>();


    @BindView(R.id.list)
    XListView mXListView;
    private DynamicAdapter mDynamicAdapter;
    List<FriendModel.ResultBean.DataBean> dynamicModelList = new ArrayList<>();


    boolean isRef = true;
    int curPageCount = 0;//当前页数


    SwipeRefreshLayout mSwipeRefreshLayout;

    private View vHead;//头部广告条
    RecyclerView mTopRecyclerView;

    MyAdapter adapter;
    private KProgressHUD hud;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_friend, null);
        vHead = View.inflate(getContext(), R.layout.friend_list_head_ab, null);
        ButterKnife.bind(this, view);
        EventBus.getDefault().register(this);


        initListView();

        return view;
    }

    public String getTime() {
        return new SimpleDateFormat("MM-dd HH:mm", Locale.CHINA).format(new Date());
    }

    private void initListView() {

        vHead = View.inflate(getContext(), R.layout.friend_list_head_ab, null);
        mXListView.addHeaderView(vHead);
        mXListView.setPullRefreshEnable(true);
        mXListView.setPullLoadEnable(false);
        mXListView.setAutoLoadEnable(true);
        mXListView.setXListViewListener(this);
        mXListView.setRefreshTime(getTime());
        adapter = new MyAdapter(getContext(), dynamicModelList);
        mXListView.setAdapter(adapter);


        showProgress("加载中...");
        loadData(null);

        initPostDynamic();
    }


    public void showProgress(String message) {
        if (hud == null) {
            hud = KProgressHUD.create(getContext())
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                    .setLabel(message)
                    .setCancellable(true);
        }
        if (!hud.isShowing()) {
            hud.show();
        }
    }

    public void hideProgress() {
        if (hud != null && hud.isShowing()) {
            hud.dismiss();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
//        loadDatas();
    }

    void loadDatas() {
        initListView();
        initPostDynamic();
    }

    private void loadData(final UpRefUpdateListener listener) {
        //post请求简洁版实现
        HttpParams params = new HttpParams();
        if (UtilTools.LoginJudge()) {
            params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(getContext(), AppConst.TOKEN, ""));
        }
        curPageCount++;
        params.put("page", curPageCount);
        RxVolley.post(StaticClass.FriendAdsURL, params, new HttpCallback() {
            @Override
            public void onSuccess(String t) {

                allData = GsonUtils.GsonToBean(t, FriendModel.class);


                if (allData.getCode() == AppConst.TOKENERROR) {
                    getActivity().startActivity(new Intent(getContext(),LoginActivity.class));
                    return;
                }

                if (allData.getCode() == 200) {


                    if (isRef == true) {
                        absLists = allData.getResult().getAds();

                        initAbs();
                    }

                    dynamicModelList.addAll(allData.getResult().getData());

                    if (allData.getResult().getData().size() > 0) {
                        adapter.notifyDataSetChanged();
                    }

                    if (allData.getResult().getData().size() == 10) {
                        mXListView.setPullLoadEnable(true);
                    } else {
                        mXListView.setPullLoadEnable(false);
                    }
                } else {
                    mXListView.setPullLoadEnable(false);
                }

                mXListView.stopRefresh();
                mXListView.stopLoadMore();


                hideProgress();

            }
        });

    }


    //水平滚动条
    void initAbs() {
        mTopRecyclerView = vHead.findViewById(R.id.recyclerView);
        absAdapter = new AbsRecyclerAdater(absLists, getContext());
        LinearLayoutManager ms = new LinearLayoutManager(getContext());
        ms.setOrientation(LinearLayoutManager.HORIZONTAL);// 设置 recyclerview 布局方式为横向布局
        mTopRecyclerView.setLayoutManager(ms);
        mTopRecyclerView.setAdapter(absAdapter);
    }


    //发布动态
    void initPostDynamic() {

        ivAddDynamic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (UtilTools.LoginJudge()) {
                    startActivity(new Intent(getActivity(), AddDynamicActivity.class));
                } else {
                    startActivity(new Intent(getActivity(), LoginActivity.class));
                }
            }
        });

    }

    //初始化动态列表
    boolean is_one_load = false;//

    void initDynamicList() {
//        if (!is_one_load) {
////            listView.addHeaderView(vHead);
////            mDynamicAdapter = new DynamicAdapter(getActivity(), getContext(), dynamicModelList, listView);
////            listView.setAdapter(mDynamicAdapter);
//            is_one_load = true;
//        } else {
////            listView.setAdapter(new DynamicAdapter(getActivity(), getContext(), dynamicModelList, listView));
//        }


    }


    void initHeadData() {
        mTopRecyclerView = vHead.findViewById(R.id.recyclerView);

        absAdapter = new AbsRecyclerAdater(absLists, getContext());
        LinearLayoutManager ms = new LinearLayoutManager(getContext());
        ms.setOrientation(LinearLayoutManager.HORIZONTAL);// 设置 recyclerview 布局方式为横向布局
        //     LinearLayoutManager 种 含有3 种布局样式  第一个就是最常用的 1.横向 , 2. 竖向,3.偏移
        mTopRecyclerView.setLayoutManager(ms);  //给RecyClerView 添加设置好的布局样式
        mTopRecyclerView.setAdapter(absAdapter);
    }

    @Subscribe
    public void onEventMainThread(String event) {
        if (event.equals("add")) {
            dynamicModelList.clear();
            isRef = true;
            curPageCount = 0;
            loadData(null);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh() {
        curPageCount = 0;
        isRef = true;
        dynamicModelList.clear();
        mXListView.setPullLoadEnable(true);
        loadData(null);
    }

    @Override
    public void onLoadMore() {
        isRef = false;
        loadData(null);
    }


    class MyAdapter extends BaseAdapter {


        private Context context;
        private List<FriendModel.ResultBean.DataBean> dynamicModelList = new ArrayList<>();
        private LayoutInflater layoutInflater;

        public MyAdapter(Context context, List<FriendModel.ResultBean.DataBean> videoModelList) {
            this.context = context;
            this.dynamicModelList = videoModelList;
            layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return dynamicModelList.size();
        }

        @Override
        public Object getItem(int position) {
            return dynamicModelList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {


            ViewHolder viewHolder = null;
            if (viewHolder == null) {
                viewHolder = new ViewHolder();
                convertView = layoutInflater.inflate(R.layout.layout_item_dynamic, null);
                viewHolder.root = (LinearLayout) convertView.findViewById(R.id.root);
                viewHolder.ivAvatar = (CircleImageView) convertView.findViewById(R.id.ivIcon);
                viewHolder.tvName = (TextView) convertView.findViewById(R.id.tvName);
                viewHolder.tvContent = (TextView) convertView.findViewById(R.id.tvContent);
                viewHolder.gridView = (GridViewForScrollView) convertView.findViewById(R.id.picGridView);
                viewHolder.tvTime = (TextView) convertView.findViewById(R.id.tvTime);
                viewHolder.ivPraise = (ImageView) convertView.findViewById(R.id.ivPraise);
                viewHolder.tvPraise = (TextView) convertView.findViewById(R.id.tvPraise);
                viewHolder.tvComment = (TextView) convertView.findViewById(R.id.tvComment);
                viewHolder.llPinglun = (RelativeLayout) convertView.findViewById(R.id.pinglun);
                viewHolder.iv_vip = convertView.findViewById(R.id.icon_vip);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

            List<String> urlList = new ArrayList<>();
            urlList = dynamicModelList.get(position).getImages();
            //用户头像
            PicassoUtils.loadImageView(context, dynamicModelList.get(position).getPublish_user().getAvatar(),viewHolder.ivAvatar);
            viewHolder.ivAvatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (UtilTools.LoginJudge()) {
                        Intent intent = new Intent(context, DynamicDetailsActivity_new.class);
                        intent.putExtra("user_id", dynamicModelList.get(position).getPublish_user().getUser_id() + "");
                        context.startActivity(intent);
                    } else {
                        startActivity(new Intent(context, LoginActivity.class));
                    }


                }
            });


            //名称
            viewHolder.tvName.setText(dynamicModelList.get(position).getPublish_user().getUsername());
            viewHolder.tvName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (UtilTools.LoginJudge()) {
                        Intent intent = new Intent(context, DynamicDetailsActivity_new.class);
                        intent.putExtra("user_id", dynamicModelList.get(position).getPublish_user().getUser_id() + "");
                        context.startActivity(intent);
                    } else {
                        startActivity(new Intent(context, LoginActivity.class));
                    }
                }
            });
            //发布内容
            viewHolder.tvContent.setText(dynamicModelList.get(position).getContent());


//        urlList = dynamicModelList.get(position).getImages();
            //发布的图片
//        viewHolder.gridView.setAdapter(new ImageAdapter(mActivity,context, urlList));
//        viewHolder.gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//            }
//        });

            final List<ImageArrayModel> imgs = new ArrayList<>();
//
            for (int i = 0; i < dynamicModelList.get(position).getImage_array().size(); i++) {
                ImageArrayModel model = new ImageArrayModel();
                model.setImage_url(dynamicModelList.get(position).getImage_array().get(i).getImage_url());
                model.setThumbnail(dynamicModelList.get(position).getImage_array().get(i).getThumbnail());
                imgs.add(model);
            }


            int resource_type = dynamicModelList.get(position).getType();
            String video_str = dynamicModelList.get(position).getVideo_url();


//            System.out.println("resource_type:" + allData.getResult().getData().get(position).getContent());
//            System.out.println("video_str:" + allData.getResult().getData().get(position).getVideo_url());

            viewHolder.gridView.setAdapter(new ImageAdapter(getActivity(), context, imgs, resource_type, video_str));


            //时间
            viewHolder.tvTime.setText(dynamicModelList.get(position).getPublish_time().toString());

            //点赞数
            final int[] pinglunCount = {Integer.parseInt(dynamicModelList.get(position).getLike_count())};
            //点赞
            final int[] like = {dynamicModelList.get(position).getIs_like()};
            if (like[0] == 1) {
                viewHolder.ivPraise.setSelected(true);
            }
            //点赞的点击事件
            final ViewHolder finalViewHolder1 = viewHolder;
            viewHolder.ivPraise.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    if (!UtilTools.LoginJudge()) {
                        CustomToast.INSTANCE.showToast("请先登录");
                        return;
                    }

                    //post请求简洁版实现
                    HttpParams params = new HttpParams();
                    params.putHeaders("Authorization", "Bearer " + ShareUtils.getString(context, AppConst.TOKEN, ""));
                    params.put("resource_id", dynamicModelList.get(position).getTweet_id());
                    params.put("resource_type", 2);


                    RxVolley.post(StaticClass.DianZan, params, new HttpCallback() {
                        @Override
                        public void onSuccess(String t) {
                            DianZhanModel dianZhanModel = GsonUtils.GsonToBean(t, DianZhanModel.class);

                            if (dianZhanModel.getCode() == AppConst.TOKENERROR) {
                                getActivity().startActivity(new Intent(getContext(),LoginActivity.class));
                                return;
                            }

                            CustomToast.INSTANCE.showToast(dianZhanModel.getStatus());
                            if (dianZhanModel.getCode() == 200) {
                                if (dianZhanModel.getResult().getIs_like() == 1) {
                                    finalViewHolder1.ivPraise.setSelected(true);
//                                        int count = Integer.parseInt(dynamicModelList.get(position).getLike_count()) + 1;
                                    pinglunCount[0]++;
                                    finalViewHolder1.tvPraise.setText(pinglunCount[0] + "");
                                    like[0] = 1;
                                } else {
                                    finalViewHolder1.ivPraise.setSelected(false);
//                                    int count = Integer.parseInt(dynamicModelList.get(position).getLike_count());
                                    pinglunCount[0]--;
                                    finalViewHolder1.tvPraise.setText(pinglunCount[0] + "");
                                    like[0] = 0;
                                }
                            } else {
                                finalViewHolder1.ivPraise.setSelected(false);
                                like[0] = 0;
                            }
                        }
                    });
                }
            });
            //点赞数
            viewHolder.tvPraise.setText(dynamicModelList.get(position).getLike_count());

            //说说评论数
            viewHolder.tvComment.setText(dynamicModelList.get(position).getComment_count());

//        评论界面
            viewHolder.llPinglun.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(context, DynamicDetailsActivity.class);
                    Bundle bundle = new Bundle();

                    DynamicDetailsPingLunModel model = new DynamicDetailsPingLunModel();
                    DynamicDetailsPingLunModel.PublishUserBean model_user = new DynamicDetailsPingLunModel.PublishUserBean();

                    model.setContent(dynamicModelList.get(position).getContent());
                    model.setPublish_time(dynamicModelList.get(position).getPublish_time());
                    model.setIs_like(like[0]);
                    model.setTweet_id(dynamicModelList.get(position).getTweet_id());
                    model.setLike_count(pinglunCount[0] + "");
                    model.setComment_count(dynamicModelList.get(position).getComment_count());
                    model_user.setAvatar(dynamicModelList.get(position).getPublish_user().getAvatar());
                    model_user.setUsername(dynamicModelList.get(position).getPublish_user().getUsername());


                    model.setPublish_user(model_user);


                    bundle.putSerializable("data", model);


                    intent.putExtras(bundle);
                    context.startActivity(intent);
                }
            });


//            L.d("authid:" + dynamicModelList.get(position).getPublish_user().getIs_authenticated());

            if (dynamicModelList.get(position).getPublish_user().getIs_authenticated() == 1) {
                viewHolder.iv_vip.setVisibility(View.VISIBLE);
            } else {
                viewHolder.iv_vip.setVisibility(View.GONE);
            }
            return convertView;
        }

        class ViewHolder {
            LinearLayout root;
            private CircleImageView ivAvatar;
            private TextView tvName;
            private TextView tvContent;
            private GridViewForScrollView gridView;
            private TextView tvTime;
            private ImageView ivPraise;
            private TextView tvPraise;
            private TextView tvComment;
            private RelativeLayout llPinglun;
            private ImageView iv_vip;
        }
    }
}
